<template>
    <div>
        <el-card>
            <div slot="header">批量创建主播</div>
            <pre>如何找到从小葫芦的主播网址中找到平台编号和主播编号
举例:
http://www.xiaohulu.com/Anchor/details.html?plat=6&roomid=10666
                                                 ⬆         ⬆
                                               平台编号    主播编号
            </pre>
            <p>
                主播级别：
                <el-tag v-for="(level,key) in anchorLevels" :key="key">{{key + ' - ' + level.name}}</el-tag>
            </p>
            <p>
                平台编号：
                <el-tag v-for="(p,key) in platforms" :key="key" type="success">{{key + ' - ' + p.name}}</el-tag>
            </p>
            <pre>* 第一列 主播名称<br>
* 第二列 主播所在平台的小葫芦编号<br>
* 第三列 主播级别编号<br>
* 第四列 主播的直播间网址<br>
  第五列 主播的小葫芦编号(可以留空，则每天不会对这个主播采集小葫芦的数据)<br>
！不要复制表头！
            </pre>
            <el-input type="textarea"
                      v-model="originalText"
                      :autosize="{minRows: 5, maxRows: 8}" placeholder="请复制Excel内容到这里"/>
            <my-alert ref="alert"/>
            <p>
                <el-button type="primary" @click="submit" :disabled="!canSubmit">提交</el-button>
                <el-button @click="$router.push('/anchor')">返回</el-button>
            </p>
        </el-card>
        <el-card>
            <div slot="header">预览（一共{{textLines()}}行，有效解析{{form.length}}行）</div>
            <el-table :data="form" border>
                <el-table-column type="index" width="50"/>
                <el-table-column label="主播名称" prop="name"/>
                <el-table-column label="小葫芦平台编号">
                    <template slot-scope="scope">
                        {{ scope.row.platform_type + ' - ' + platforms[scope.row.platform_type].name}}
                    </template>
                </el-table-column>
                <el-table-column label="主播编号" prop="_id"/>
                <el-table-column label="主播级别">
                    <template slot-scope="scope">
                        {{anchorLevels[scope.row.level_id].name}}
                    </template>
                </el-table-column>
                <el-table-column label="主播直播间网址">
                    <template slot-scope="scope">
                        <a :href="scope.row.url" target="_blank">链接</a>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
</template>


<script>
    import MyAlert from "../component/my_alert";

    export default {
        components: {MyAlert},
        data() {
            return {
                platforms: [],
                anchorLevels: [],
                originalText: '',
                form: [],
                canSubmit: false,
                success: false,
            }
        },
        methods: {
            fetch() {
                this.$http.get('/api/xiaohulu/level').then(({data}) => {
                    this.anchorLevels = _.keyBy(data, 'id');
                });
                this.$http.get('/api/platform').then(({data}) => {
                    data = _.sortBy(data.filter(d => !!d.type), 'type');
                    this.platforms = _.keyBy(data, 'type');
                });
            },
            submit() {
                this.$confirm('已经确认数据没有错误？', {type: 'warning'})
                    .then(() => {
                        this.$http.post('/api/xiaohulu/bulk-create-anchor', this.form)
                            .then(({data}) => {
                                this.$refs.alert.success(`提交成功，成功录入 ${data.create_mount} 个主播`, 5000);
                                this.originalText = '';
                                this.form = [];
                                this.$message.success('成功添加 ' + data.create_mount + ' 个主播');
                            })
                            .catch(err => {
                                this.$refs.alert.error(err.response.data);
                                this.$message.error(err.response.data);
                            });
                    })
                    .catch(() => {

                    });
            },
            textLines() {
                if (this.originalText.length === 0)
                    return 0;
                return this.originalText.split('\n').length;
            }
        },
        watch: {
            originalText() {
                this.$refs.alert.hide();
                if (this.originalText.length === 0)
                    return;
                try {
                    formatText.call(this, this.originalText);
                } catch (e) {
                    this.form = [];
                    this.$refs.alert.error(e.message);
                }
                this.canSubmit = this.form.length > 0;
            }
        },
        mounted() {
            this.fetch();
        }
    }

    function formatText(text) {
        const lines = text.split("\n");
        this.form = lines.map((line, i) => {
            const data = line.trim().split(/[\s\t]+/);
            let name = data[0], platform_type = data[1], level_id = data[2], url = data[3], _id = data[4], error;

            if (!(data.length === 4 || data.length === 5))
                error = `第${i + 1}行的内容出现问题，请检查。`;

            if (!this.platforms[platform_type])
                error = `第${i + 1}行的 平台编号 无法识别`;
            else if (!this.anchorLevels[level_id])
                error = `第${i + 1}行的 主播级别 无法识别`;

            if (error)
                throw new Error(error);

            return {name, platform_type, platform_id: this.platforms[platform_type].id, _id, level_id, url};
        });
    }
</script>

<style scoped>

</style>